package cn.emailChat.ai.consumer.util;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Properties;


/**
 * @Description 基于 SMTPTransport 复用，复用smtp连接，但是是单线程串行复用
 * @Author susu
 * @Date 2025/8/19
 */

@Slf4j
@Component
public class SmtpSender {

    // ===== 配置项：字段 @Value 注入 =====
    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.port}")
    private int port;

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;

    @Value("${spring.mail.properties.mail.smtp.ssl.enable:true}")
    private boolean useSsl;

    @Value("${spring.mail.properties.mail.smtp.starttls.enable:false}")
    private boolean starttls;

    @Value("${spring.mail.properties.mail.smtp.connectiontimeout:10000}")
    private int connTimeoutMs;

    @Value("${spring.mail.properties.mail.smtp.timeout:15000}")
    private int readTimeoutMs;

    @Value("${spring.mail.properties.mail.smtp.writetimeout:15000}")
    private int writeTimeoutMs;

    // ===== 运行时对象 =====
    private Session session;
    private volatile Transport transport;

    // 初始化：根据配置创建 Session
    @PostConstruct
    public void init() {
        Properties p = new Properties();
        p.put("mail.smtp.auth", "true");
        p.put("mail.smtp.ssl.enable", String.valueOf(useSsl));          // 465: true
        p.put("mail.smtp.starttls.enable", String.valueOf(starttls));   // 587: true
        p.put("mail.smtp.connectiontimeout", String.valueOf(connTimeoutMs));
        p.put("mail.smtp.timeout", String.valueOf(readTimeoutMs));
        p.put("mail.smtp.writetimeout", String.valueOf(writeTimeoutMs));
        // 如需调试可打开：p.put("mail.debug", "true");

        session = Session.getInstance(p);
        log.info("[SmtpSender] Session 初始化完成: host={}, port={}, ssl={}, starttls={}",
                host, port, useSsl, starttls);
    }

    /** 串行复用一个 SMTP 连接；失败自动重连一次 */
    public synchronized void sendText(String from, String to, String subject, String body) throws Exception {
        ensureConnected();

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "UTF-8");
        msg.setSentDate(new Date());
        msg.setText(body, "UTF-8");

        try {
            transport.sendMessage(msg, msg.getAllRecipients());
        } catch (MessagingException first) {
            log.warn("[SmtpSender] 发送失败，准备重连后重发: {}", first.getMessage());
            safeClose();
            ensureConnected();
            transport.sendMessage(msg, msg.getAllRecipients());
        }
    }

    private void ensureConnected() throws MessagingException {
        if (transport == null || !transport.isConnected()) {
            transport = session.getTransport("smtp"); // 实际由 jakarta-mail 提供实现
            transport.connect(host, port, username, password);
            log.info("[SmtpSender] SMTP 已连接 {}:{}", host, port);
        }
    }

    private void safeClose() {
        try { if (transport != null) transport.close(); } catch (Exception ignored) {}
        transport = null;
    }

    @PreDestroy
    public void shutdown() {
        safeClose();
        log.info("[SmtpSender] 连接已关闭");
    }
}